<?php

class ModelService extends \BaseService{

    /**
     * 增加模型
     * @param [string] $name        模型名
     * @param [string] $tableName   模型名对应表名
     * @return [array] 异常信息
     */
    public static function add($data){
        try{
            Schema::create($data['tableName'],function($table){
                $table->increments('id');
                $table->integer('category_id');
                $table->string('title');
                $table->timestamps();
            });

            $model = new Model;
            $model->name=$data['name'];
            $model->table_name=$data['tableName'];
            $model->save();
            $modelId = $model->id;

            $field = new Field;
            $field->name='title';
            $field->type='string';
            $field->display_name='标题';
            $field->model_id=$modelId;
            $field->save();

            $modelName = studly_case($data['tableName']);
            $table = '$table';
            $content = <<<model
<?php

class {$modelName} extends \Eloquent{

    protected {$table} = '{$data['tableName']}'; 

} 
model;
            File::put(app_path().'/models/'.$modelName.'.php', $content);
        }catch(Exception $e){
            Schema::dropIfExists($data['tableName']);
            throw new ModelAddException;
        }
    }


    /**
     * 更新模型
     * @param [int]  $id     模型id
     * @param [string] $name 模型名
     * @return [array] 异常信息
     */
    public static function update($data){
        $model = Model::find($data['id']);
        if(!isset($model)){
            throw new ModelNoFoundException;
        }
        $model->name=$data['name'];
        $model->save();
        return self::getResult('成功更新模型');
    }

    /**
     * 删除模型
     * @param  [int]  $id 模型id
     * @return [array] 异常信息
     */
    public static function delete($id){
        try{
            $model = Model::find($id);
            if(!isset($model)){
                throw new ModelNoFoundException;
            }
            if(File::exists(app_path().'/models/'.$model['table_name'].'.php')){
                File::delete(app_path().'/models/'.$model[
            'table_name'].'.php');
            }
            $model->delete();
        }catch(Exception $e){
            return new ModelDeleteException;
        }
        return self::getResult('成功删除模型');
    }

}